<?php
/**
 * 前端登录类
 * @author 肖小平
 *
 */
class LoginAction extends Action{
	/**
	 * 登录操作
	 */
	public function login(){
		if($_POST){
			$data['username'] = $_POST['username'];
			$data['password']= md5($_POST['password']);
			$where['phone'] = $_POST['username'];
			$where['password']= md5($_POST['password']);
			$re = M('User')->where($data)->find();
			$re1 = M('User')->where($where)->find();
			if($re){
				session('login',1);//存入登录状态，用于判断是否登录
				session('username',$re['username']);
				session('u_nickname',$re['nickname']);
				session('user_id',$re['id']);
				echo 1;
			}else if($re1){
				session('login',1);//存入登录状态，用于判断是否登录
				session('username',$re1['username']);
				session('u_nickname',$re1['nickname']);
				session('user_id',$re1['id']);
				echo 1;
			}else{
				echo 0;
			}
			exit;
		}	
		$this->display();
	}
	/*
	 * 修改密码
	 */
	public function update_password(){
		if($_POST){
			$_POST['password'] = md5($_POST['password']);
			$re = M('User')->where('id='.$_SESSION['user_id'])->save($_POST);
			if($re){
				echo 1;
			}else{
				echo 0;
			}
			exit;
		}
		$this->display();
	}
	/*
	 * 忘记密码
	 */
	public function forget_password(){
		if($_POST){
			$re = M('User')->where('phone='.$_POST['phone'])->find();
			if(!$re){
				echo 2;
				exit;
			}
			$re1 = M('User')->where('issue='."'".$_POST['issue']."'"." and answer="."'".$_POST['answer']."'")->find();
			if(!$re1){
				echo 3;
				exit;
			}
			$data['password'] = md5($_POST['password']);
			$obj = M('User')->where('issue='."'".$_POST['issue']."'"." and answer="."'".$_POST['answer']."'"." and phone=".$_POST['phone'])->find();
			$re2 = M('User')->where('issue='."'".$_POST['issue']."'"." and answer="."'".$_POST['answer']."'"." and phone=".$_POST['phone'])->save($data);
			if($re2){
				echo 1;
				session('login',1);//存入登录状态，用于判断是否登录
				session('username',$obj['username']);
				session('u_nickname',$obj['nickname']);
				session('user_id',$obj['id']);
				exit;
			}else{
				echo 0;
				exit;
			}
		}
		$list = M('Issue')->select();
		$this->assign('list',$list);
		$this->display();
	}
	/*
	 * 注册操作
	 */
	public function register(){
		if($_POST){
			if (!preg_match('/^[a-zA-Z0-9_]{6,20}$/', $_POST['username'])){
				echo 2;
				exit;
			}
			if (!preg_match('/^1[3|4|5|7|8]\d{9}$/', $_POST['phone'])){
				echo 3;
				exit;
			}
			if (!preg_match('/^[a-zA-Z0-9]{6,20}$/', $_POST['password'])){
				echo 4;
				exit;
			}
			$_POST['password'] = md5($_POST['password']);
			$_POST['time'] = time();
			$re = M('User')->add($_POST);	
			if($re){
				session('login',1);//存入登录状态，用于判断是否登录
				session('username',$_POST['username']);
				session('u_nickname','');
				session('user_id',$re);
				echo 1;
			}else{
				echo 0;
			}
			exit;
		}
		$list = M('Issue')->select();
		$this->assign('list',$list);
		$this->display();
	}
}

?>